<template>
	<view class="my-page">
		<navbarVue title="个人信息"></navbarVue>
		<view class="my-bg-img">
			<image src="/static/img/my-bg.png"></image>
		</view>
		<view class="user-info">
			<view class="user-item">
				<view class="user-img">
					<image :src="userInfo.avatarUrl" mode="" @click="handleModify"></image>
					<ImageSelectorVue ref="imageSelectorRef" upload-url="/resource/oss/upload"
						@imageSelected="onImageSelected" @uploadSuccess="onUploadSuccess"
						@uploadFailed="onUploadFailed" />
					<view class="Cut" @click="handleCut" v-if="userType === '1'">
						<image src="/static/icon/icon-15.png" mode=""></image>
					</view>
				</view>
				<!-- 访客 -->
				<view class="input-box" v-if="userType === '1'">
					<view class="user-input">
						<view class="">您的姓名：</view>
						<view class="">
							<uv-input placeholder="请输入姓名" color="#333" fontSize="16px" border="none" inputAlign="right"
								v-model="userInfo.nickName"></uv-input>
						</view>
					</view>
					<view class="user-input">
						<view class="">您的手机号：</view>
						<view class="">
							<uv-input placeholder="请输入手机号" color="#333" fontSize="16px" border="none" inputAlign="right"
								v-model="userInfo.phonenumber" type="number" maxlength="11"></uv-input>
						</view>
					</view>
					<picker mode="selector" :range="certificateTypes" range-key="label"
						@change="handleCertificateChange">
						<view class="user-input">
							<view class="">证件类型：</view>
							<view class="selected-value">
								<text :class="{ 
					            'default-text': !selectedItem.label,
					            'selected-text': selectedItem.label 
					          }">
									{{ selectedItem?.label || '请选择证件类型' }}
								</text>
								<uv-icon name="arrow-right" color="#999" size="16" class="arrow-icon" />

							</view>
						</view>
					</picker>

					<view class="user-input">
						<view class="">证件号码：</view>
						<view class="">
							<uv-input placeholder="填写证件号码" color="#333" fontSize="16px" border="none" inputAlign="right"
								v-model="userInfo.idCardNumber" maxlength="18"></uv-input>
						</view>
					</view>
					<view class="user-input">
						<view class="">公司/单位：</view>
						<view class="">
							<uv-input placeholder="填写公司/单位名称" color="#333" fontSize="16px" border="none"
								inputAlign="right" v-model="userInfo.departName"></uv-input>
						</view>
					</view>
				</view>

				<!-- 被访客 -->
				<view class="input-box" v-else>
					<view class="user-input">
						<view class="">工号：</view>
						<view class="user-text">
							{{userInfo.userName}}
							<!-- 	<uv-input placeholder="暂无工号" color="#999" fontSize="16px" border="none" inputAlign="right"
								v-model="userInfo.userName" readonly></uv-input> -->
						</view>
					</view>
					<view class="user-input">
						<view class="">您的姓名：</view>
						<view class="user-text">
							{{userInfo.nickName}}
						</view>
					</view>
					<view class="user-input">
						<view class="">任职公司：</view>
						<view class="user-text">
							{{userInfo.firmName}}
						</view>
					</view>
					<view class="user-input">
						<view class="">任职部门：</view>
						<view class="user-text">
							{{userInfo.deptName}}
						</view>
					</view>
				</view>

				<view class="agree-box">
					<!-- 已同意协议复选框（常用于注册/登录场景） -->
					<div>
						<uv-checkbox-group v-model="isAgreeProtocol" @change="onProtocolChange">
							<uv-checkbox :customStyle="{ 
				        marginBottom: '8px',
				        display: 'flex', 
				        alignItems: 'center'
				      }" label="我已阅读并同意" name="agreeProtocol" :disabled="isProtocolDisabled">
							</uv-checkbox>
						</uv-checkbox-group>
					</div>
					<div @click="hanldeToPrivacy"><text style="color: #2B75E2; margin: 0 2px;">《隐私政策》</text></div>
				</view>

				<view class="sub-save" @click="updateUser">
					保存
				</view>

			</view>

		</view>
		<uv-popup ref="visitPopup" class="custom-popup " style="z-index: 99;" :closeable="true" round="10px"
			@change="handleClose">
			<view class="visit-popup">
				<view class="form-item">
					<view class="form-title">工号<span class="heavy">*</span></view>
					<view class="">
						<uv-input placeholder="请输入工号" border="bottom" class="force-style-input" color="#333"
							fontSize="16px" :customStyle="inputCustomStyle" placeholderStyle="font-weight: normal;"
							type="text" v-model="swiForm.jobNumber"></uv-input>
					</view>
				</view>
				<view class="form-item">
					<view class="form-title">密码<span class="heavy">*</span></view>
					<view class="">
						<uni-easyinput type="password" v-model="swiForm.password" placeholder="请输入密码" border="bottom"
							class="force-style-input" color="#333" :customStyle="{ 
						    paddingLeft: '0px', 
						    marginLeft: '0px',}"
							placeholderStyle="font-weight: normal; font-size: 16px; padding-left: 0; text-indent: 0;"
							:inputBorder="false"></uni-easyinput>

						<!-- 	<uv-input placeholder="请输入密码" border="bottom" class="force-style-input" color="#333"
							fontSize="16px" :customStyle="inputCustomStyle" placeholderStyle="font-weight: normal;"
							:type="showPassword ? 'text' : 'password'" v-model="swiForm.password">
							<template #suffix>
								<uv-icon :name="showPassword ? 'eye-off' : 'eye'" @click="handleIsShow"></uv-icon>
							</template>
						</uv-input> -->

					</view>
					<div style="width: 100%;border: 1px solid #efecec;"></div>
				</view>
				<view class="form-item" @click="handleToReg">
					<view class="NextStep">登录</view>
				</view>
			</view>
		</uv-popup>



		<TabBar :currentIndex="2"></TabBar>
	</view>
</template>

<script setup>
	import {
		$get,
		$post,
		$put
	} from "@/utils/request.js"
	import {
		ref,
		watch,
		onMounted
	} from 'vue';
	import {
		onShow,
		onShareAppMessage,
		onShareTimeline
	} from '@dcloudio/uni-app';
	import {
		convertDepartmentsPublic,
		validatePhone,
		validateIdCard
	} from '@/utils/verifyMethod.js'
	import {
		useStore
	} from 'vuex'
	import TabBar from '../../components/TabBar/TabBar.vue';
	import navbarVue from '../../components/navbar/navbar.vue';
	import ImageSelectorVue from '@/components/ImageSelector/ImageSelector.vue';
	import methods from '@/utils/methods.js'


	onShow(() => {
		departmentList()
	})
	const store = useStore()


	//1访客 2被访客 3保安
	const userType = ref('1')
	watch(
		() => store.getters.getRoles,
		(newgetRoles) => {
			if (Array.isArray(newgetRoles) && newgetRoles.length > 0) {
				userType.value = newgetRoles[0];
			}
		}, {
			deep: true
		}
	);

	onShareAppMessage(() => {
		return {
			title: '访客小程序分享', // 分享标题
			path: '/pages/index/index',
		}
	})

	onShareTimeline(() => {
		return {
			title: '访客小程序分享',
			path: '/pages/index/index'
		}
	})
	onMounted(() => {
		const savedAgreeStatus = uni.getStorageSync('visitor_agree_protocol');
		if (savedAgreeStatus) {
			isAgreeProtocol.value = true; // 强制保持已勾选
			isProtocolDisabled.value = true; // 强制禁用，只读
		}
	});



	// 身份证类型列表查询
	const certificateTypes = ref([]);
	const selectedItem = ref(null);
	const handleCertificateChange = (e) => {
		const selectedIndex = e.detail.value;
		selectedItem.value = certificateTypes.value[selectedIndex];
		userInfo.value.idCardType = selectedItem.value.id;
	}

	// 修改头像
	const imageUrl = ref('');
	const imageSelectorRef = ref(null);
	// 点击事件触发子组件
	const handleModify = () => {
		imageSelectorRef.value?.openImageSelector();
	};
	// 图片选择成功回调
	const onImageSelected = (path) => {
		// userInfo.value.avatarUrl = path;
		// console.log(imageUrl.value);
	};
	// 上传成功回调
	const onUploadSuccess = (result) => {
		userInfo.value.avatarUrl = result.data.url
		userInfo.value.avatar = result.data.ossId
	};
	// 上传失败回调
	const onUploadFailed = (error) => {
		uni.showToast({
			icon: "error",
			title: '上传失败'
		})
	};


	//用户信息
	const userInfo = ref({})
	const departmentList = () => {
		$get('/system/dict/data/type/visitor_card_type').then(res => { //身份证类型列表
			const news = convertDepartmentsPublic(res.data)
			certificateTypes.value = news
		})

		$get('/system/user/getInfo')
			.then(res => {
				userInfo.value = res.data.user || {};
				store.commit('setUserInfo', res.data.user || {});
				store.commit('setRoles', res.data.roles || []);
				// 初始化证件选择项（用接口数据或默认空对象）
				selectedItem.value = res.data.user ? {
					id: res.data.user.idCardType,
					label: res.data.user.idCardTypeName
				} : {
					id: '',
					label: ''
				};
			})
			.catch(error => {
				userInfo.value = {};
				store.commit('setUserInfo', {});
				store.commit('setRoles', []);
				selectedItem.value = {
					id: '',
					label: ''
				};
			});
	}

	const hanldeToPrivacy = () => {
		uni.navigateTo({
			url: '/pages/my/Privacy/Privacy'
		})
	}


	//仅允许“未禁用时”修改勾选状态，禁用后无法改变
	const onProtocolChange = (value) => {
		if (isProtocolDisabled.value) {
			isAgreeProtocol.value = true; // 强制恢复勾选
			return;
		}
		// 未禁用时，同步勾选状态（用户可自由勾选/取消）
		isAgreeProtocol.value = value.includes('agreeProtocol');
	};

	// 协议勾选状态（初始从本地读取，默认false）
	const isAgreeProtocol = ref(false);
	// 控制复选框是否禁用（勾选后禁用，只读）
	const isProtocolDisabled = ref(false);

	const updateUser = () => {
		if (!isAgreeProtocol.value) {
			uni.showToast({
				title: '请先阅读并同意用户协议和隐私政策',
				icon: 'none'
			});
			return false;
		}

		const {
			idCardNumber,
			idCardType,
			phonenumber
		} = userInfo.value;
		let isValid = true;

		// 手机号验证（保持原样）
		if (phonenumber && !validatePhone(phonenumber)) {
			isValid = false;
			uni.showToast({
				icon: 'none',
				title: '请输入正确的手机号'
			});
		}

		// 身份证验证（保持原样）
		if (idCardNumber) {
			console.log(idCardNumber);
			if (!idCardType) {
				isValid = false;
				uni.showToast({
					icon: 'none',
					title: '请选择证件类型'
				});
			} else if (!validateIdCard(idCardNumber)) {
				isValid = false;
				uni.showToast({
					icon: 'none',
					title: '请输入正确的身份证号码'
				});
			}
		}

		if (isValid) {
			uni.showLoading({
				title: '保存中...',
				mask: true
			});
			$post('/system/user/visitorUserEdit', userInfo.value).then(res => {
				uni.hideLoading();
				if (res.code == 200) {
					// 仅保存成功后，才存储协议状态并禁用复选框
					uni.setStorageSync('visitor_agree_protocol', true);
					isProtocolDisabled.value = true; // 禁用后无法取消勾选

					departmentList()
					setTimeout(() => {
						uni.showToast({
							icon: "success",
							title: '保存成功',
						});
					}, 1000);

				} else {
					uni.showToast({
						icon: "none",
						title: res.msg || '保存失败'
					});

				}
			}).catch(error => {
				uni.hideLoading();
				uni.showToast({
					icon: "none",
					title: '网络异常，请稍后重试'
				});

			})
		}

		return isValid;
	};



	// 账号切换弹窗
	const visitPopup = ref(null)
	const handleCut = () => {
		visitPopup.value.open()
	}
	// 关闭弹出层
	const handleClose = (e) => {
		if (e.show === false) {
			swiForm.value.jobNumber = ''
			swiForm.value.password = ''
		}

	}


	const showPassword = ref(false);

	const handleIsShow = () => {
		showPassword.value = !showPassword.value; // 正确：用 .value 切换值
	};



	const swiForm = ref({
		jobNumber: '',
		password: ''
	});

	const handleToReg = () => {

		if (swiForm.value.jobNumber == '') {
			uni.showToast({
				icon: 'none',
				title: "请输入工号"
			});
			return;
		}
		if (swiForm.value.password == '') {
			uni.showToast({
				icon: 'none',
				title: "请输入密码"
			});
			return;
		}

		$post(`/system/user/jobNumber?jobNumber=${swiForm.value.jobNumber}&password=${swiForm.value.password}`).then(
			res => {
				if (res.code == 200) {
					methods.login()
					departmentList()
					handleClose({
						show: false
					});
					visitPopup.value.close()
					uni.showToast({
						icon: 'none',
						title: "登录成功"
					});
				} else {
					uni.showToast({
						icon: 'none',
						title: res.msg
					});
				}
			})
	};




	//输入框
	const inputCustomStyle = ref({
		padding: '12px 6px',
		borderRadius: '6px',
		borderBottom: '1px solid #ddd',
		fontSize: '16px',
		fontWeight: '600',
		color: '#333',
	})
</script>

<style lang="scss">
	.my-page {
		width: 100vw;
		height: 100vh;
		background-color: #ECF1F9;
	}

	.my-bg-img {
		width: 100vw;
		height: 300px;
		position: relative;

		image {
			width: 100%;
			height: 100%;
			object-fit: cover;
		}

		.individual-title {
			position: absolute;
			top: 20%;
			left: 50%;
			transform: translate(-50%);
			font-size: var(--font-16);
			color: var(--color-ff);

		}
	}

	.user-info {
		width: 100%;
		transform: translateY(-200rpx);
		display: flex;
		justify-content: center;

		.user-item {
			width: 94%;
			background-color: #fff;
			border-radius: 10px;
			padding: 10px;
			box-sizing: border-box;
			position: relative;


			.Cut {
				width: 25px;
				height: 25px;
				position: absolute;
				right: 0%;
				bottom: 0%;

				image {
					width: 100%;
					height: 100%;
				}
			}

			.user-img {
				width: 90px;
				height: 90px;
				border-radius: 50%;
				border: 2px solid #fff;
				position: absolute;
				left: 50%;
				top: -10%;
				transform: translate(-50%, );

				image {
					width: 100%;
					height: 100%;
					border-radius: 50%;
				}



			}


			.input-box {
				margin-top: 18%;
				padding: 20px 10px;
				box-sizing: border-box;

				.user-input {
					width: 100%;
					height: 30px;
					padding: 25px 0px;
					box-sizing: border-box;
					display: flex;
					align-items: center;
					justify-content: space-between;
					border-bottom: 1px solid #d5d5d5;
					color: var(--color-333);

					.selected-value .default-text {
						color: #C0C4CC;
					}

					.selected-value .selected-text {
						font-size: var(--font-16);
						// font-weight: 600;
						color: var(--color-666);
					}

					.selected-value {
						display: flex;
						align-items: center;
						gap: 6px;
					}
					
					.user-text{
						color:#C0C4CC;
						font-size: 16px;
					}

				}
			}

			.agree-box {
				width: 100%;
				height: 30px;
				display: flex;
				padding: 0px 16px;
				box-sizing: border-box;

			}

			.sub-save {
				width: 120px;
				height: 40px;
				margin: 20rpx auto;
				text-align: center;
				line-height: 40px;
				background-color: #2B75E2;
				border-radius: 50px;
				color: var(--color-ff);
			}




		}

	}

	// 用户弹窗

	.visit-popup {
		width: 90vw;
		padding: 30px;
		box-sizing: border-box;

		.user-input {
			width: 100%;
			padding: 16px 0px;
			box-sizing: border-box;
			display: flex;
			flex-direction: column;
			gap: 10px;
			border-bottom: 1px solid #d5d5d5;
			color: var(--color-333);

			.form-title {
				color: var(--color-666);
				font-size: var(--font-16);


			}

			// .selected-value {
			// 	display: flex;
			// 	align-items: center;
			// 	justify-content: space-between;
			// 	gap: 6px;

			// 	.default-text {
			// 		color: var(--color-666);
			// 	}

			// 	.selected-text {
			// 		font-size: var(--font-16);
			// 		font-weight: 600;
			// 		color: var(--color-333);
			// 	}
			// }

		}

		.form-item {
			margin-top: 20px;




			.heavy {
				color: red;
				font-size: var(--font-16);
			}

			.form-title {
				color: var(--color-666);
				font-size: var(--font-16);
			}

			::v-deep .input-placeholder {
				color: #999 !important;

			}

			.NextStep {
				width: 100%;
				height: 40px;
				text-align: center;
				line-height: 40px;
				color: var(--color-ff);
				font-size: var(--font-16);
				background-color: #2b74e2;
				border-radius: 50px;
				font-weight: 600;
			}


		}
	}
</style>